<?php
namespace App\Api\Controllers\Agent;


use App\Api\Controllers\BaseController;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Store;
use App\Models\StoreDayAllOrder;
use App\Models\UserDayOrder;
use App\Models\UserMonthOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class OrderController extends BaseController
{

    public function order(Request $request)
    {

        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id', '');
            $user_id = $request->get('user_id', '');
            $pay_status = $request->get('pay_status', '');
            $ways_source = $request->get('ways_source', '');
            $company = $request->get('company', '');

            $ways_type = $request->get('ways_type', '');
            $time_start = $request->get('time_start', date('Y-m-d 00:00:00', time()));
            $time_end = $request->get('time_end', date('Y-m-d 23:59:59', time()));

            $amount_start = $request->get('amount_start', '');
            $amount_end = $request->get('amount_end', '');

            $re_data = [
                'time_start' => $time_start,
                'time_end' => $time_end,
            ];
            $check_data = [
                'time_start' => '订单开始时间',
                'time_end' => '订单结束时间',
            ];
            $check = $this->check_required($re_data, $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }


            //限制时间
            $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
            $day = 31;
            if ($date > $day) {
                return json_encode([
                    'status' => 2,
                    'message' => '时间筛选不能超过' . $day . '天'
                ]);
            }


            $sort = $request->get('sort', '');
            $out_trade_no = $request->get('out_trade_no', '');
            $trade_no = $request->get('trade_no', '');

            $obj = DB::table('orders');
            $where = [];

            if ($user_id == "") {
                $user_id = $user->user_id;
            }
            $user_ids = $this->getSubIds($user_id);

            if (1) {
                $where[] = ['ways_type', '!=', '2005'];
            }

            if ($amount_start) {
                $where[] = ['total_amount', '>=', $amount_start];
            }

            if ($amount_end) {
                $where[] = ['total_amount', '<=', $amount_end];
            }

            if ($pay_status) {
                $where[] = ['pay_status', '=', $pay_status];
            }
            if ($store_id) {
                $where[] = ['store_id', '=', $store_id];
            }
            if ($company) {
                $where[] = ['company', '=', $company];
            }
            if ($ways_source) {
                if (in_array($ways_source, ['alipay_face', 'weixin_face'])) {
                    $where[] = ['pay_method', '=', $ways_source];

                } else {
                    $where[] = ['ways_source', '=', $ways_source];
                }
            }
            if ($ways_type) {
                $where[] = ['ways_type', '=', $ways_type];
            }
            if ($time_start) {
                $where[] = ['created_at', '>=', $time_start];
            }
            if ($time_end) {
                $where[] = ['created_at', '<=', $time_end];
            }


            if ($sort) {
                $obj = $obj->where($where)
                    ->whereIn('user_id', $user_ids)
                    ->orderBy('total_amount', $sort);
            } elseif ($out_trade_no || $trade_no) {
                if ($out_trade_no) {
                    $where1[] = ['out_trade_no', $out_trade_no];
                }

                if ($trade_no) {
                    $where1[] = ['trade_no', $trade_no];
                }

                $obj = $obj->where($where1)
                    ->whereIn('user_id', $user_ids)
                    ->orderBy('created_at', 'desc');


            } else {
                $obj = $obj->where($where)
                    ->whereIn('user_id', $user_ids)
                    ->orderBy('created_at', 'desc');
            }


            $this->t = $obj->count();
            $data = $this->page($obj)->get();
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }


    public function order_info(Request $request)
    {
        try {
            $user = $this->parseToken();
            $out_trade_no = $request->get('out_trade_no', '');
            $data = Order::where('out_trade_no', $out_trade_no)->first();
            if (!$data) {
                $this->status = 2;
                $this->message = '订单号不存在';
                return $this->format();
            }
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }


    //对账统计-比较全-实时
    public function order_count(Request $request)
    {
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id', '');
            $user_id = $request->get('user_id', '');
            $ways_source = $request->get('ways_source', '');
            $company = $request->get('company', '');
            $time_start = $request->get('time_start', '');
            $time_end = $request->get('time_end', '');
            $return_type = $request->get('return_type', '01');
            $amount_start = $request->get('amount_start', '');
            $amount_end = $request->get('amount_end', '');


            //限制时间
            $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
            $day = 31;
            if ($date > $day) {
                return json_encode([
                    'status' => 2,
                    'message' => '时间筛选不能超过' . $day . '天'
                ]);
            }


            $check_data = [
                'time_start' => '开始时间',
                'time_end' => '结束时间',
            ];
            $where = [];
            $whereIn = [];
            $store_ids = [];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }
            //条件查询
            if ($time_start) {
                $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                $where[] = ['created_at', '>=', $time_start];
            }
            if ($time_end) {
                $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                $where[] = ['created_at', '<=', $time_end];
            }


            if ($amount_start) {
                $where[] = ['total_amount', '>=', $amount_start];
            }

            if ($amount_end) {
                $where[] = ['total_amount', '<=', $amount_end];
            }


            if ($company) {
                $where[] = ['company', $company];
            }

            if ($ways_source) {
                if (in_array($ways_source, ['alipay_face', 'weixin_face'])) {
                    $where[] = ['pay_method', '=', $ways_source];

                } else {
                    $where[] = ['ways_source', '=', $ways_source];
                }
            }
            if ($store_id) {
                $where[] = ['store_id', $store_id];
            }
            if ($user_id) {

                $user_ids = [
                    [
                        'user_id' => $user_id,
                    ]
                ];

                $user_ids = $this->getSubIds($user_id);

            } else {
                $user_ids = $this->getSubIds($user->user_id);
            }


            //区间
            $e_order = '0.00';


            $order_data = Order::whereIn('user_id', $user_ids)
                ->where($where)
                ->whereIn('pay_status', [1, 6, 3])//成功+退款
                ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');


            $refund_obj = Order::whereIn('user_id', $user_ids)
                ->where($where)
                ->whereIn('pay_status', [6, 3])//退款
                ->select('total_amount');

            //总的
            $total_amount = $order_data->sum('total_amount');//交易金额
            $refund_amount = $refund_obj->sum('total_amount');//退款金额
            $fee_amount = $order_data->sum('fee_amount');//结算服务费/手续费
            $mdiscount_amount = $order_data->sum('mdiscount_amount');//商家优惠金额
            $get_amount = $total_amount - $refund_amount - $mdiscount_amount;//商家实收，交易金额-退款金额
            $receipt_amount = $get_amount - $fee_amount;//实际净额，实收-手续费
            $e_order = '' . $e_order . '';
            $total_count = '' . count($order_data->get()) . '';
            $refund_count = count($refund_obj->get());


            $data = [
                'total_amount' => number_format($total_amount, 2, '.', ''),//交易金额
                'total_count' => '' . $total_count . '',//交易笔数
                'refund_count' => '' . $refund_count . '',//退款金额
                'get_amount' => number_format($get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'refund_amount' => number_format($refund_amount, 2, '.', ''),//退款金额
                'receipt_amount' => number_format($receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'fee_amount' => number_format($fee_amount, 2, '.', ''),//结算服务费/手续费
                'mdiscount_amount' => number_format($mdiscount_amount, 2, '.', ''),
            ];
            //附加流水详情
            if ($return_type == "02") {
                $obj = DB::table('orders');
                $obj = $obj->where($where)
                    ->whereIn('user_id', $user_ids)
                    ->orderBy('updated_at', 'desc');
                $this->t = $obj->count();
                $data['order_list'] = $this->page($obj)->get();
            }

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }


    //对账统计-比较全-非实时
    public function order_count1(Request $request)
    {
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id', '');
            $user_id = $request->get('user_id', '');
            $ways_source = $request->get('ways_source', '');
            $company = $request->get('company', '');
            $time_start = $request->get('time_start', '');
            $time_end = $request->get('time_end', '');
            $return_type = $request->get('return_type', '01');


            //限制时间
            $date = (strtotime($time_end) - strtotime($time_start)) / 86400;
            $day = 31;
            if ($date > $day) {
                return json_encode([
                    'status' => 2,
                    'message' => '时间筛选不能超过' . $day . '天'
                ]);
            }


            $check_data = [
                'time_start' => '开始时间',
                'time_end' => '结束时间',
            ];
            $where = [];
            $whereIn = [];
            $store_ids = [];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }
            //条件查询
            if ($time_start) {
                $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                $where[] = ['created_at', '>=', $time_start];
            }
            if ($time_end) {
                $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                $where[] = ['created_at', '<=', $time_end];
            }

            if ($company) {
                $where[] = ['company', $company];
            }

            if ($ways_source) {
                $where[] = ['ways_source', $ways_source];
            }
            if ($store_id) {
                $where[] = ['store_id', $store_id];
            }
            if ($user_id) {
                $user_ids = $this->getSubIds($user_id);

            } else {
                $user_ids = $this->getSubIds($user->user_id);
            }


            //区间
            $time_start1 = date("Ymd", strtotime($time_start));
            $time_end1 = date("Ymd", strtotime($time_end));


            $order_data = UserDayOrder::whereBetween('day', [$time_start1, $time_end1])
                ->whereIn('user_id', $user_ids)
                ->select(
                    'total_amount',
                    'order_sum',
                    'refund_amount',
                    'refund_count',
                    'fee_amount');

            //总的
            $total_amount = $order_data->sum('total_amount');//交易金额
            $refund_amount = $order_data->sum('refund_amount');//退款金额
            $fee_amount = $order_data->sum('fee_amount');//结算服务费/手续费
            $mdiscount_amount = '0.00';//商家优惠金额
            $get_amount = $total_amount - $refund_amount - $mdiscount_amount;//商家实收，交易金额-退款金额
            $receipt_amount = $get_amount - $fee_amount;//实际净额，实收-手续费
            $total_count = $order_data->sum('order_sum');
            $refund_count = $order_data->sum('refund_count');


            $data = [
                'total_amount' => number_format($total_amount, 2, '.', ''),//交易金额
                'total_count' => '' . $total_count . '',//交易笔数
                'refund_count' => '' . $refund_count . '',//退款金额
                'get_amount' => number_format($get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'refund_amount' => number_format($refund_amount, 2, '.', ''),//退款金额
                'receipt_amount' => number_format($receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'fee_amount' => number_format($fee_amount, 2, '.', ''),//结算服务费/手续费
                'mdiscount_amount' => number_format($mdiscount_amount, 2, '.', ''),
            ];
            //附加流水详情
            if ($return_type == "02") {
                $obj = DB::table('orders');
                $obj = $obj->where($where)
                    ->whereIn('user_id', $user_ids)
                    ->orderBy('created_at', 'desc');
                $this->t = $obj->count();
                $data['order_list'] = $this->page($obj)->get();
            }

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }


    //数据对账-比较全-非实时
    public function order_data(Request $request)
    {
        try {
            $user = $this->parseToken();

            //下级账户
            $user_ids = $this->getSubIds($user->user_id);

            $sub_user = count($user_ids);

            $stores = Store::whereIn('user_id', $user_ids)
                ->select('id')
                ->get();
            $sub_store = count($stores);


            if (0) {
                //今天数据
                $UserDayOrder_a = UserDayOrder::where('day', date('Ymd', time()))
                    ->whereIn('user_id', $user_ids)
                    ->select('total_amount', 'order_sum');

                $day_amount = $UserDayOrder_a->sum('total_amount');
                $day_count = $UserDayOrder_a->sum('order_sum');

                //昨天数据
                $UserDayOrder_b = UserDayOrder::where('day', date('Ymd', strtotime("-1 day")))
                    ->whereIn('user_id', $user_ids)
                    ->select('total_amount', 'order_sum');

                $old_day_amount = $UserDayOrder_b->sum('total_amount');
                $old_day_count = $UserDayOrder_b->sum('order_sum');


            } else {
                $order_data = Order::whereIn('user_id', $user_ids)
                    ->where('created_at', '>=', date('Y-m-d 00:00:00', time()))
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->select('total_amount');


                $day_amount = $order_data->sum('total_amount');
                $day_count = count($order_data->get());


                //昨天数据

                $order_data_o = Order::whereIn('user_id', $user_ids)
                    ->where('created_at', '>=', date('Y-m-d 00:00:00', strtotime("-1 day")))
                    ->where('created_at', '<=', date('Y-m-d 23:59:59', strtotime("-1 day")))
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->select('total_amount');


                $old_day_amount = $order_data_o->sum('total_amount');
                $old_day_count = count($order_data_o->get());

            }


            //本月
            $UserDayOrder_c = UserMonthOrder::whereIn('user_id', $user_ids)
                ->where('month', date('Ym', time()))
                ->select('total_amount', 'order_sum');

            $month_amount = $UserDayOrder_c->sum('total_amount');
            $month_count = $UserDayOrder_c->sum('order_sum');


            //上个月
            $UserDayOrder_d = UserMonthOrder::whereIn('user_id', $user_ids)
                ->where('month', date('Ym', strtotime('-1 month')))
                ->select('total_amount', 'order_sum');

            $old_month_amount = $UserDayOrder_d->sum('total_amount');
            $old_month_count = $UserDayOrder_d->sum('order_sum');


            return json_encode([
                'status' => 1,
                'data' => [
                    'sub_user' => '' . $sub_user . '',
                    'sub_store' => '' . $sub_store . '',
                    'day_amount' => '' . $day_amount . '',
                    'day_count' => '' . $day_count . '',
                    'old_day_amount' => '' . $old_day_amount . '',
                    'old_day_count' => '' . $old_day_count . '',
                    'month_amount' => '' . $month_amount . '',
                    'month_count' => '' . $month_count . '',
                    'old_month_amount' => '' . $old_month_amount . '',
                    'old_month_count' => '' . $old_month_count . '',
                ]

            ]);
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }


    //门店数据
    // public function store_order_data(Request $request)
    // {
    //     try {
    //         $user = $this->parseToken();
    //         $store_id = $request->get('store_id', '');
    //         $d = date('Ymd', strtotime("-1 day"));
    //         $day = $request->get('day', '');
    //         $day = isset($day) ? $day : $d;
    //         $time_start = $request->get('time_start', '');
    //         $time_end = $request->get('time_end', '');
    //         $order_count = $request->get('order_count', '');
    //         $order_money = $request->get('order_money', '');
    //         $user_ids = $this->getSubIds($user->user_id);

    //         $where = [];


    //         if ($day) {
    //             $where[] = ['store_day_all_orders.day', '=', $day];
    //         }


    //         if ($store_id) {
    //             $store_ids = [
    //                 'store_id' => $store_id
    //             ];
    //         } else {

    //             $store_ids = Store::whereIn('user_id', $user_ids)->select('store_id')->get();
    //             if ($store_ids->isEmpty()) {
    //                 $store_ids = [
    //                     'store_id' => '1'
    //                 ];
    //             } else {
    //                 $store_ids = $store_ids->toArray();
    //             }
    //         }


    //         $obj = StoreDayAllOrder::join('stores', 'store_day_all_orders.store_id', '=', 'stores.store_id')
    //             ->where($where)
    //             ->whereIn('store_day_all_orders.store_id', $store_ids)
    //             ->orderBy('store_day_all_orders.order_sum', $order_count)
    //             ->orderBy('store_day_all_orders.total_amount', $order_money)
    //             ->select('stores.store_short_name', 'store_day_all_orders.total_amount', 'store_day_all_orders.order_sum', 'store_day_all_orders.store_id');


    //         $this->t = $obj->count();
    //         $data = $this->page($obj)->get();
    //         $this->status = 1;
    //         $this->message = '数据返回成功';
    //         return $this->format($data);

    //     } catch (\Exception $exception) {
    //         $this->status = -1;
    //         $this->message = $exception->getMessage();
    //         return $this->format();
    //     }
    // }


}
